package com.example.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;


/*
 * In this example, we launch 'HelloActivity' as the main activity which displays a text
 * box and a send button
 * On clicking the button, the user entered text is passed to another activity (DisplayMessageActivity)
 * which displays the user's messsage, along with the count of number of times user passed on the message.
 * 
 * count is preserved in a bundle so that the value is maintained across transitions between activities
 * ... aka, across the restarting the HelloActivity
 * 
 * In addition, the application registers for Telephony notifications for listening and displaying
 * GSM signal strength on request.
 */
public class HelloActivity extends Activity {

	public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
	public final static String EXTRA_SEND_COUNT = "com.example.myfirstapp.SEND_COUNT";
	static final String NUM_MESSAGE_SENDS = "num_message_sends";
	static final String PREFERENCE_FILE = "com.example.myfirstapp.PREF_FILE";
	static final String LOG = "mylog";
	private SignalListener ss;
	int num_sends;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	
    	Context context;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello);
        
        // Try to fetch from persistent storage if our activity was
        // destroyed by user (by pressing back button)
        context = this;
        SharedPreferences sharedPref = context.getSharedPreferences(PREFERENCE_FILE, Context.MODE_PRIVATE);
        num_sends = sharedPref.getInt(NUM_MESSAGE_SENDS, -1);
        
        if (num_sends == -1) {
        	if (savedInstanceState != null) {
        		num_sends = savedInstanceState.getInt(NUM_MESSAGE_SENDS);
        		Log.v(LOG, "onCreate: Fetched from savedInstance. num_sends = " + num_sends);
        	} else {
        		num_sends = 0;
        		Log.v(LOG, "onCreate: Starting afresh. num_sends = " + num_sends);
        	}
        } else {
        	Log.v(LOG, "onCreate: Fetched from sharedPref. num_sends = " + num_sends);
        }
        
        // Start listening to signal strength
        ss = new SignalListener();
        ((TelephonyManager)getSystemService(TELEPHONY_SERVICE)).listen(ss, SignalListener.LISTEN_SIGNAL_STRENGTHS);
    }
    
    
    // Called when activity shutting down completely.
    // Usually not required to be implemented, cleanup done in onPause/onStop methods.
    @Override
    public void onDestroy() {
       	// Save to persistent storage
    	// Save num_sends to a persistent file
    	
    	Context context = this;
    	SharedPreferences sharedPref = context.getSharedPreferences(PREFERENCE_FILE, Context.MODE_PRIVATE);
    	SharedPreferences.Editor editor = sharedPref.edit();
    	editor.putInt(NUM_MESSAGE_SENDS, num_sends);
    	editor.commit();
    	
    	Log.v(LOG, "onDestroy: comitted num_sends = " + num_sends);
    	
    	super.onDestroy();
    }
    
    /*
     * onPause: User leaving the activity, might return later
     * Should use this method to:
     * a) Stop animations or other CPU consuming activities
     * b) Commit unsaved changes, if applicable
     * c) Release system resources, like broadcast receivers, sensors (GPS etc), camera
     * d) One should avoid heavy CPU CPU work (writing large data to databases) during onPause
     *    as it could slow down the visible transition to the next activity => defer till onStop
     */
    public void onPause() {
    	super.onPause();
    }
    
    /*
     * onResume: Counterpart of onPause
     * Note that onResume is also called right after onCreate
     */
    public void onResume() {
    	super.onResume();
    }
    
    /*
     * onStop: User switched to another app and your activity UI is completely removed from screen.
     * Called when:
     * a) User switches to another app from 'recent-apps' window
     * b) User starts another activity from ur app's current activity
     * c) User receives a phone call
     * 
     * onStop should be used for high CPU intensive cleanups, than using onPause
     * If all resources are cleaned up during onPause only, one may not implement onStop/onRestart
     * at all.
     * 
     * Even when the activity is stopped, activity stil remains in memory. System also tracks the
     * current state of each View, so user entered input (say in text widget) is retained.
     * 
     * Even if system destroys the activity, its state is saved in bundle, and restores them
     * when user navigates back to the same instance of the activity.
     * 
     * In extreme cases, system might not call onDestroy while killing your app. So its always
     * better to release all resources in onStop which might leak memory.
     * 
     * Technically onRestart is the counterpart of onStop. But since onStart is called both
     * while re-starting or fresh-starting an app, its better to use onStart as the counterpart
     * of onStop
     */
    @Override
    protected void onStop() {
    	super.onStop();
    }
    
    /*
     * onRestart: Technical counterpart of onStop
     */
    @Override
    protected void onRestart() {
    	super.onRestart();
    }

    /*
     * onStart: 'Recommended' counterpart of onStop
     */
    @Override
    protected void onStart() {
    	super.onStart();
    }
    
    /*
     * onDestroy: Activity going to be destroyed.
     * Called in following cases:
     * a) User presses the back button  (normal app behavior)
     * b) Activity itself calls finish() (normal app behavior)
     * c) Activity hasn't been used for long time
     * d) Another foreground activity needs resources which system is running out of.
     * 
     * In first 2 cases above, system forgets the activity state.
     * In other cases (destruction due to system constraints), the activity View state is stored in a bundle object.
     * 
     * Developer should override onSaveInstanceState() to pass on additional information to be stored in the bundle
     * The bundle is passed to the user when activity is recreated, both in onCreate and onRestoreInstanceState
     */
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
    	savedInstanceState.putInt(EXTRA_SEND_COUNT, num_sends);
    	Log.v(LOG, "onSaveInstanceState: put num_sends = " + num_sends);
    	super.onSaveInstanceState(savedInstanceState); //save View object state
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.hello, menu);
        return true;
    }
    
    public void sendMessage(View view) {
    	Intent intent = new Intent(this, DisplayMessageActivity.class);
    	EditText editbox = (EditText)findViewById(R.id.edit_message);
    	String message = editbox.getText().toString();
    	num_sends++;
    	
     	// Pass on to the next activity
    	intent.putExtra(EXTRA_SEND_COUNT, num_sends);
    	intent.putExtra(EXTRA_MESSAGE, message);
    	
    	startActivity(intent);
    }
    
    public void sendSignalStrength(View view) {
    	Intent intent = new Intent(this, DisplayMessageActivity.class);
    	
    	int strength = ss.ss;
    	String message = "Current signal strength";
    	
    	
    	
    	
     	// Pass on to the next activity
    	intent.putExtra(EXTRA_SEND_COUNT, strength);
    	intent.putExtra(EXTRA_MESSAGE, message);
    	
    	startActivity(intent);
    }
    
}